package logs

import (
	"common/config"
	"common/utils"
	"fmt"
	"github.com/charmbracelet/log"
	"io/fs"
	"os"
	"time"
)

var logger *log.Logger

func InitLog(appName string) {
	logger = log.New(os.Stderr)
	if config.Conf.Log.Level == "DEBUG" {
		logger.SetLevel(log.DebugLevel)
	} else {
		logger.SetLevel(log.InfoLevel)
		logger.SetOutput(LogFile(config.Conf.Log.File))
	}
	logger.SetPrefix(fmt.Sprintf("[%s]", appName))
	logger.SetReportTimestamp(true)
	logger.SetTimeFormat(time.DateTime)
}

func Fatal(format string, values ...any) {
	if len(values) == 0 {
		logger.Fatal(format)
	} else {
		logger.Fatalf(format, values...)
	}
}
func Info(format string, values ...any) {
	if len(values) == 0 {
		logger.Info(format)
	} else {
		logger.Infof(format, values...)
	}
}
func Warn(format string, values ...any) {
	if len(values) == 0 {
		logger.Warn(format)
	} else {
		logger.Warnf(format, values...)
	}
}
func Debug(format string, values ...any) {
	if len(values) == 0 {
		logger.Debug(format)
	} else {
		logger.Debugf(format, values...)
	}
}
func Error(format string, values ...any) {
	if len(values) == 0 {
		logger.Error(format)
	} else {
		logger.Errorf(format, values...)
	}
}

func LogFile(file string) *os.File {
	day := utils.TimeOrDateAsYear(0, "", "d")
	ym := utils.TimeOrDateAsYear(0, "", "Ym")
	directory := fmt.Sprintf("../%s/%s/%s/", config.Conf.Log.Src, file, ym)
	fileName := fmt.Sprintf("%s.log", day)
	fileSrc := directory + fileName

	if err := os.MkdirAll(directory, fs.ModePerm); err != nil {
		Fatal("logs mkdir file failed,err:%v,address=%v,file=%v,fileSrc=%v", err, directory, fileName, fileSrc)
		return nil
	}
	logFile, err := os.Create(fileSrc)
	if err != nil {
		Fatal("logs open file failed,err:%v", err)
		return nil
	}
	return logFile
}
